package com.hainatong.shiphelper.module.warehouse.fragment;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.widget.ImageView;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrManager;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.hainatong.shiphelper.App;
import com.hainatong.shiphelper.Constants;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentExpendlistViewBinding;
import com.hainatong.shiphelper.mainhome.ComFragmentActivity;
import com.hainatong.shiphelper.module.warehouse.adapter.ShelfExpandableAdapter;
import com.hainatong.shiphelper.module.warehouse.entity.ImpaShelfCodeBean;
import com.hainatong.shiphelper.module.warehouse.entity.ShipWareHouseBean;
import com.hainatong.shiphelper.module.warehouse.entity.WareShelfBean;
import com.hainatong.shiphelper.module.warehouse.viewmodel.WareHouseViewModel;
import com.hainatong.shiphelper.pictureselector.PictureBean;
import com.hainatong.shiphelper.pictureselector.PictureSelector;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.shiphelper.widget.LoadingDialog;


public class SelectShelfFragment extends MvvmLazyFragment<FragmentExpendlistViewBinding, WareHouseViewModel>
{
    private static String SELET_SHELF_TAG = "SelectShelfFragment";

    private LoadingDialog loadingDialog;

    private ShipWareHouseBean wareHouse;
    //ShelfAdapter
    private ShelfExpandableAdapter  shelfAdapter;

    private String selectShelfUuid = "";

    public static SelectShelfFragment newInstance(String scanCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( SELET_SHELF_TAG , scanCode );
        SelectShelfFragment shelf = new SelectShelfFragment();
        shelf.setArguments( bundle );
        return  shelf;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        if(  args != null )
        {
            String wareStr = args.getString(SELET_SHELF_TAG , "");
            if(!StringUtils.isEmpty( wareStr ))
            {
                wareHouse = GsonUtil.json2Obj( wareStr, ShipWareHouseBean.class);
            }
        }
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_expendlist_view;
    }

    @Override
    public int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void initView(View view)
    {
        loadingDialog = new LoadingDialog(getActivity() , getString( R.string.loading ) );
        shelfAdapter = new ShelfExpandableAdapter(getActivity());

        //RecyclerViewHelper.addLinerLayoutMgrNoDecoration(viewDataBinding.recyclerview);

        viewDataBinding.expandListview.setAdapter( shelfAdapter );
        viewDataBinding.expandListview.setOnChildClickListener( (parent, v, groupPosition, childPosition, id) -> {

            LogUtils.e( "shelfAdapter  groupPosition = " + groupPosition + "  childPosition  = " + childPosition );

            WareShelfBean.ChildrenBean child = (WareShelfBean.ChildrenBean) shelfAdapter.getChild(groupPosition, childPosition);

            selectShelfUuid = child.getUuid();
            // 选择完  货架 扫描 物资 code
            startScanQrcode();
            /*
            BaseNode  child = shelfAdapter.getItem(position);
            if(  child instanceof WareShelfBean.ChildrenBean)
            {}
            */
            return false;
        });
    }

    @Override
    protected void lazyLoad()
    {
        if(ObjectUtils.isNotEmpty( wareHouse ))
        {
            // 查询 货架
            viewModel.queryShelfByWareName(  wareHouse.getWareHouseName() );
        }

        viewModel.getShelfResult().observe( this ,result -> {
            loadingDialog.hide();
            if( result.isSuccess() )
            {
               if( result.getData() != null )
               {
                   List<WareShelfBean>  shelfResultList = result.getData();
                   shelfAdapter.setWareShelfBeans( shelfResultList );
                   /*
                   List<BaseNode> shelfList = getShelfNodeList( shelfResultList );
                   shelfAdapter.setList( shelfList );
                   */
               }
            }
            else
            {
                ToastUtils.showShort( result.getMsg() );
            }
        } );
    }

        /*
    // 模拟新增node
        mRecyclerView.postDelayed(new Runnable() {
    @Override
    public void run() {
        SecondNode seNode = new SecondNode(new ArrayList<BaseNode>(), "Second Node(This is added)");
        SecondNode seNode2 = new SecondNode(new ArrayList<BaseNode>(), "Second Node(This is added)");
        List<SecondNode> nodes = new ArrayList<>();
        nodes.add(seNode);
        nodes.add(seNode2);
        //第一个夫node，位置为子node的3号位置
        adapter.nodeAddData(adapter.getData().get(0), 2, nodes);
//                adapter.nodeSetData(adapter.getData().get(0), 2, seNode2);
//                adapter.nodeReplaceChildData(adapter.getData().get(0), nodes);
        Toast.makeText(BashRecyActivity.this,"新插入了两个node",Toast.LENGTH_LONG).show();
    }
}, 2000);

    */

    private  List<BaseNode> getShelfNodeList( List<WareShelfBean>  shelfResultList )
    {
        List<BaseNode> shelfList = new ArrayList<>();
        if( shelfResultList != null && !shelfResultList.isEmpty()  )
        {
            for(WareShelfBean shelf : shelfResultList  )
            {
               shelfList.add( shelf);
               /*
               if( shelf.getChildren() != null && !shelf.getChildren().isEmpty() )
               {
                   for( WareShelfBean.ChildrenBean child:  shelf.getChildren() )
                   {
                       shelfList.add( child);
                   }
               }
               */
            }
        }
        return shelfList;
    }




    public void startScanQrcode()
    {
        QrManager.getInstance().init( App.getScanQrConfigByType(2) ).startScan(getActivity(), new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(ScanResult result)
            {
                LogUtils.e(TAG, "onScanSuccess: " + result.getContent());
                if( result.getType() == ScanResult.CODE_QR)
                {
                    //ToastUtils.showShort( result.getContent() );

                    //拿到物资 code   跳转 入库 详情
                    ImpaShelfCodeBean codeBean = new ImpaShelfCodeBean( selectShelfUuid ,result.getContent() );
                    //跳转 入库 添加商品
                    ComFragmentActivity.startViewByParam( getActivity(),Constants.VIEW_TYPE_RUKU_TASK, GsonUtil.obj2json(codeBean),true );
                }
                else
                {
                    ToastUtils.showShort( result.getContent() );
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        loadingDialog.dismiss();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        /* 选择图片 结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE)
        {
            if (data != null)
            {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                File imgFile = new File( pictureBean.getPath() );
                String errorImgPath = pictureBean.getPath();
                Glide.with(getActivity())
                     .load( imgFile )
                     .into( new ImageView(getActivity()));

                //实际开发中将图片上传到服务器成功后需要删除全部缓存图片（即裁剪后的无用图片）
                //FileUtils.deleteAllCacheImage(this);
            }
        }
    }
}
